/**
 * 
 */
package ru.olympus.antonyhands.ao.client.widgets;

import ru.olympus.antonyhands.ao.client.AOHelperServiceAsync;
import ru.olympus.antonyhands.ao.shared.util.StringUtilities;

import com.google.gwt.dom.client.Document;
import com.google.gwt.event.dom.client.ChangeEvent;
import com.google.gwt.user.client.ui.ListBox;

/**
 * @author AntonyHands
 * @since 08.03.2012
 */
public abstract class BasicListBox extends ListBox {

	private AOHelperServiceAsync _service;
	private String _defaultValue;

	protected BasicListBox(AOHelperServiceAsync service, String defaultValue) {
		_service = service;
		_defaultValue = defaultValue;
	}

	protected AOHelperServiceAsync getService() {
		return _service;
	}

	public String getCurrentValueCode() {
		int index = getSelectedIndex();
		return index == -1 ? null : getValue(index);
	}

	protected void updateCurrentValue()
	{
		if (getItemCount() > 0)
        {
            setSelectedIndex(0);
            if (!StringUtilities.isEmpty(_defaultValue))
            	for (int i = 0; i < getItemCount(); i++)
            		if (_defaultValue.equals(getValue(i)))
            		{
            			setSelectedIndex(i);
            			break;
            		}
            ChangeEvent.fireNativeEvent(Document.get().createChangeEvent(), this);
        }
	}
}
